package com.lyt.util;

import com.lyt.ViewModel.Wx.Item;
import com.lyt.vo.ItemVo;
import org.junit.Test;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: lyt
 * @Date: 2023/04/29/20:14
 * @Description:
 */
public class BeanUtil {
//    根据属性名称进行转换
    public static <T> T beanConvert(Object provide,T Target){
        Class voClass=provide.getClass();
        Class pojoClass=Target.getClass();

        for (Field field : pojoClass.getDeclaredFields()) {
            for (Field declaredField : voClass.getDeclaredFields()) {
                //如果对象名匹配成功的话  就赋值
//                System.out.println("对象转换中");
                declaredField.setAccessible(true);
                field.setAccessible(true);

//                System.out.println("目标对象的字段名称"+field);
                if(declaredField.getName().equals(field.getName())){
                    try {
                        if(declaredField.get(provide)!=null){
                            field.set(Target,declaredField.get(provide));
                        }
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }

        }

        return Target;
    }

    @Test
    public void testUtils(){
        Item item=new Item();
        List list=new ArrayList();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        ItemVo itemVo=new ItemVo("11","22");
        try {
            System.out.println("转换前的结果 :"+item);
//beanConvert()            System.out.println("转换后的结果 :"+item);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
